package io.renren.modules.generator.controller;

import java.util.*;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSONObject;
import io.renren.modules.generator.entity.*;
import io.renren.modules.generator.service.*;
import io.renren.modules.sys.controller.AbstractController;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.service.SysUserRoleService;
import io.renren.modules.sys.service.SysUserService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;



/**
 * 
 *
 * @author author
 * @email author@gmail.com
 * @date 2021-07-01 11:12:11
 */
@RestController
@RequestMapping("generator/project")
public class ProjectController extends AbstractController {
    @Autowired
    private IndustryService industryService;
    @Autowired
    private ProjectService projectService;

    @Autowired
    private PrizeService prizeService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private CompanyService companyService;

    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Autowired
    private ScoreService scoreService;

    @Autowired
    private ProjectFileService projectFileService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("generator:project:list")
    public R list(@RequestParam Map<String, Object> params){
        SysUserEntity sessionUser = getUser();
        List<Long> roleIdList = sysUserRoleService.queryRoleIdList(sessionUser.getUserId());
        if (roleIdList.contains(2L)) {
            // 公司职员
            CompanyEntity companyEntity = companyService.getById(sessionUser.getDeptId());
            params.put("myCompany", companyEntity.getId());
        } else if (roleIdList.contains(1L)) {
            // 专家
            List<ScoreEntity> scoreEntityList = scoreService.queryByExpertId(sessionUser.getUserId().intValue());
            if (scoreEntityList != null) {
                List<Integer> projectIdList = scoreEntityList.stream().map(item -> item.getProjectId()).collect(Collectors.toList());
                params.put("projectIdList", projectIdList);
            } else {
                // 暂无分配评审的项目
                return R.ok();
            }
        }
        PageUtils page = projectService.queryPage(params);
        R result = R.ok().put("page", page);

        // 查找可用奖项
        if (roleIdList.contains(2L)) {
            CompanyEntity companyEntity = companyService.getById(sessionUser.getDeptId());
            // 公司人员角色
            List<PrizeEntity> prizes = prizeService.queryByIndustryId(companyEntity.getIndustryId());
            // 查找可用专家
            List<SysUserEntity> experts = sysUserService.queryUserByRoleIdAndDeptId(1L, companyEntity.getIndustryId());

            result.put("prizes", prizes).put("experts", experts);
        }


        return result;
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("generator:project:info")
    public R info(@PathVariable("id") Integer id){
		ProjectEntity project = projectService.getById(id);
        List<ProjectFileEntity> fileList = projectFileService.queryFileList(id);
        R put = R.ok().put("project", project).put("fileList", fileList);
        return put;
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("generator:project:save")
    public R save(@RequestBody ProjectEntity project){
        SysUserEntity sessionUser = getUser();
        CompanyEntity companyEntity = companyService.getById(sessionUser.getDeptId());
        PrizeEntity prizeEntity = prizeService.getById(project.getPrizeId());
        project.setUserId(sessionUser.getUserId().intValue());
        project.setUserName(sessionUser.getUsername());
        project.setCompanyId(sessionUser.getDeptId());
        project.setCompanyName(companyEntity.getCompanyName());
        project.setPrizeName(prizeEntity.getPrizeName());
        project.setCreateTime(new Date());
        project.setState(0);
        project.setMark("暂未评分");
        projectService.save(project);
        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("generator:project:update")
    public R update(@RequestBody ProjectEntity project){
        SysUserEntity sessionUser = getUser();
        CompanyEntity companyEntity = companyService.getById(sessionUser.getDeptId());
        PrizeEntity prizeEntity = prizeService.getById(project.getPrizeId());
        project.setUserId(sessionUser.getUserId().intValue());
        project.setUserName(sessionUser.getUsername());
        project.setCompanyId(sessionUser.getDeptId());
        project.setCompanyName(companyEntity.getCompanyName());
        project.setPrizeName(prizeEntity.getPrizeName());
        project.setState(0);
        project.setMark("暂未评分");
		projectService.updateById(project);
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("generator:project:delete")
    public R delete(@RequestBody Integer[] ids){
		projectService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

    /**
     * 提交审核
     */
    @RequestMapping("/approval/{id}")
    @RequiresPermissions("generator:project:approval")
    public R approval(@PathVariable("id") Integer id){
        ProjectEntity project = projectService.getById(id);
        project.setState(1);
        projectService.updateById(project);
        return R.ok();
    }

    /**
     * 通过
     */
    @RequestMapping("/toPass/{id}")
    @RequiresPermissions("generator:project:toPass")
    public R toPass(@PathVariable("id") Integer id){
        ProjectEntity project = projectService.getById(id);
        project.setState(2);
        projectService.updateById(project);
        return R.ok();
    }

    /**
     * 不通过
     */
    @RequestMapping("/toNoPass/{id}")
    @RequiresPermissions("generator:project:toNoPass")
    public R toNoPass(@PathVariable("id") Integer id){
        ProjectEntity project = projectService.getById(id);
        project.setState(3);
        projectService.updateById(project);
        return R.ok();
    }

    /**
     * 通过项目id查找专家和奖项列表
     * @param id
     * @return
     */
    @GetMapping("/searchExperts/{id}")
    public R searchExperts(@PathVariable("id") Integer id) {
        ProjectEntity projectEntity = projectService.getById(id);
        CompanyEntity companyEntity = companyService.getById(projectEntity.getCompanyId());
        IndustryEntity industryEntity = industryService.getById(companyEntity.getIndustryId());
        List<PrizeEntity> prizes = prizeService.queryByIndustryId(companyEntity.getIndustryId());
        List<SysUserEntity> userList = sysUserService.queryUserByRoleIdAndDeptId(1L, industryEntity.getId());
        R put = R.ok().put("userList", userList).put("prizes", prizes);
        return put;
    }


    /**
     * 分配专家
     * @param jsonObject
     * @return
     */
    @RequestMapping("/assignExperts")
    @RequiresPermissions("generator:project:assignExperts")
    public R assignExperts(@RequestBody JSONObject jsonObject) {
        Integer id = jsonObject.getInteger("id");
        if (id == null) {
            return R.error();
        }
        // 通过工程id查找专家，如果为空新增，不为空删除后新增
        List<ScoreEntity> scoreEntityList = scoreService.queryByProjectId(id);
        if (CollectionUtils.isNotEmpty(scoreEntityList)) {
            for (ScoreEntity score : scoreEntityList) {
                scoreService.removeById(score.getId());
            }
        }
        String experts = jsonObject.getString("experts");
        if (StringUtils.isBlank(experts)) {
            return R.error();
        }
        List<Integer> expertIdList = new ArrayList<>();
        if (experts.contains(",")) {
            String[] expertArr = experts.split(",");
            for (int i = 0; i < expertArr.length; i++) {
                // 过滤脏数据
                if ("[object Object]".equals(expertArr[i])) {
                    continue;
                }
                expertIdList.add(Integer.parseInt(expertArr[i]));
            }
        } else {
            expertIdList.add(Integer.parseInt(experts));
        }

        ProjectEntity projectEntity = projectService.getById(id);

        for (Integer expertId : expertIdList) {
            SysUserEntity expertUser = sysUserService.getById(expertId);
            ScoreEntity scoreEntity = new ScoreEntity();
            scoreEntity.setProjectId(id);
            scoreEntity.setProjectName(projectEntity.getProjectName());
            scoreEntity.setExpertId(expertId);
            scoreEntity.setExpertName(expertUser.getUsername());
            // 初始化为0
            scoreEntity.setMark("0");
            scoreService.save(scoreEntity);
        }
        projectEntity.setState(4);
        projectService.updateById(projectEntity);

        return R.ok();
    }
}
